# -*- coding:utf-8 -*-
from server import cache


class heart_pick:
    re = cache.re()
    def __init__(self):
        self.conn = self.re.redis

    def heart(self):
        """
        心跳检测
        逻辑:
            1)取得所有基站key
            2)取得每个key对应的状态
            3)判断状态是否为正常(非bell或dead,lose)
            4)将state<3的++,state>3的存入kill命令，状态更新为dead
        :return: 
        """
        keys = self.conn.keys("BS*")
        l = self.__key_state(keys)

        self.__jump(l)

    @re.re_batch
    def __key_state(self, keys, pipe=None):
        for k in keys:
            pipe.lindex(k, 1)
            pipe.keys(k)

    @re.re_batch
    def __jump(self, l, pipe=None):
        for i in range(len(l)):
            ba_state = l[i]
            if type(ba_state) == list:
                continue
            key = l[i + 1][0]

            if len(ba_state) < 1:
                now_need = int(ba_state) + 1
                if now_need > 90:
                    pipe.sadd("cop", key + "," + "kill")
                    pipe.lset(key, 1, "dead")
                else:
                    pipe.lset(key, 1, now_need)